<template>
  <div class="write-page">
    <div class="editor-container">
      <!-- 编辑器头部 -->
      <div class="editor-header">
        <div class="header-left">
          <el-button text @click="$router.back()" class="back-btn">
            <el-icon>
              <ArrowLeft />
            </el-icon>
            goBack
          </el-button>
        </div>

        <div class="header-right">
          <el-button @click="saveDraft" :loading="saving" :disabled="!form.title.trim() || !form.content.trim()">
            Save draft
          </el-button>
          <el-button type="primary" @click="publishArticle" :loading="publishing"
            :disabled="!form.title.trim() || !form.content.trim()">
            Publish article
          </el-button>
        </div>
      </div>

      <!-- 文章表单 -->
      <div class="editor-content">
        <!-- 标题输入 -->
        <div class="title-section">
          <el-input v-model="form.title" placeholder="Please enter the article title..." size="large" maxlength="100" show-word-limit
            class="title-input" />
        </div>

        <!-- 摘要输入 -->
        <div class="summary-section">
          <el-input v-model="form.summary" type="textarea" placeholder="Please enter an article abstract (optional)..." :rows="3" maxlength="200"
            show-word-limit class="summary-input" />
        </div>

        <!-- 话题选择 -->
        <div class="topic-section">
          <div class="section-title">Choose a topic</div>
          <div class="topic-selector">
            <el-select v-model="form.topicIds" multiple filterable remote reserve-keyword placeholder="Search and select relevant topics (up to 5)"
              :remote-method="searchTopicsRemote" :loading="topicLoading" class="topic-select"
              @change="handleTopicChange">
              <el-option v-for="topic in topicOptions" :key="topic.id" :label="topic.name" :value="topic.id">
                <div class="topic-option">
                  <div class="topic-name">{{ topic.name }}</div>
                  <div class="topic-desc">{{ topic.description }}</div>
                </div>
              </el-option>
            </el-select>

            <!-- 已选择的话题标签 -->
            <div v-if="selectedTopics.length > 0" class="selected-topics">
              <el-tag v-for="topic in selectedTopics" :key="topic.id" closable @close="removeTopicTag(topic.id)"
                class="topic-tag">
                {{ topic.name }}
              </el-tag>
            </div>
          </div>
        </div>

        <!-- 专栏选择 -->
        <div class="column-section">
          <div class="section-title">Select column (optional)</div>
          <div class="column-selector">
            <el-select v-model="form.columnId" filterable remote reserve-keyword placeholder="Search and select columns"
              :remote-method="searchColumnsRemote" :loading="columnLoading" class="column-select" clearable>
              <el-option v-for="column in columnOptions" :key="column.id" :label="column.name" :value="column.id">
                <div class="column-option">
                  <div class="column-name">{{ column.name }}</div>
                  <div class="column-desc">{{ column.description }}</div>
                </div>
              </el-option>
            </el-select>

            <!-- 已选择的专栏 -->
            <div v-if="selectedColumn" class="selected-column">
              <div class="column-info">
                <el-icon>
                  <Notebook />
                </el-icon>
                <span>{{ selectedColumn.name }}</span>
                <el-button text size="small" @click="form.columnId = null" class="remove-btn">
                  <el-icon>
                    <Close />
                  </el-icon>
                </el-button>
              </div>
            </div>
          </div>
        </div>

        <!-- 富文本编辑器 -->
        <div class="editor-section">
          <div class="section-title">Article content</div>
          <Editor v-model="form.content" />
          <!-- <div class="editor-wrapper">
            <el-input
              v-model="form.content"
              type="textarea"
              placeholder="开始写作..."
              :rows="20"
              class="content-editor"
            />
          </div> -->
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Close, Notebook } from '@element-plus/icons-vue'
import { useUserStore } from '@/stores/user'
import { createArticle, getArticleDetail, updateArticle } from '@/api/article'
import { searchTopics } from '@/api/topic'
import { getColumnList } from '@/api/column'
import Editor from '@/components/Editor/index.vue'

const route = useRoute()
const router = useRouter()
const userStore = useUserStore()

// 响应式数据
const saving = ref(false)
const publishing = ref(false)
const topicLoading = ref(false)
const columnLoading = ref(false)
const topicOptions = ref([])
const columnOptions = ref([])
const selectedTopics = ref([])
const selectedColumn = ref(null)

const form = ref({
  id: null,
  title: '',
  content: '',
  summary: '',
  coverImage: '',
  topicIds: [],
  columnId: null
})

// 生命周期
onMounted(async () => {
  if (!userStore.isLoggedIn) {
    ElMessage.warning('请先登录')
    router.push('/login')
    return
  }

  // 加载用户的专栏列表
  loadUserColumns()

  // 如果有文章ID，加载文章数据
  if (route.query.id) {
    loadArticleData(route.query.id)
  }
})

// 监听专栏选择变化
watch(() => form.value.columnId, (newColumnId) => {
  if (newColumnId) {
    selectedColumn.value = columnOptions.value.find(column => column.id === newColumnId)
  } else {
    selectedColumn.value = null
  }
})

// 方法
const loadArticleData = async (articleId) => {
  try {
    const response = await getArticleDetail(articleId)
    if (response.code === 200) {
      const article = response.data
      form.value = {
        id: article.id,
        title: article.title,
        content: article.content,
        summary: article.summary || '',
        coverImage: article.coverImage || '',
        topicIds: article.topics ? article.topics.map(t => t.id) : [],
        columnId: article.columnId || null
      }

      // 设置已选择的话题
      if (article.topics && article.topics.length > 0) {
        selectedTopics.value = article.topics.map(topic => ({
          id: topic.id,
          name: topic.name,
          description: topic.description
        }))
      }

      // 设置已选择的专栏
      if (article.columnId) {
        // 如果专栏不在当前列表中，需要加载专栏信息
        const existingColumn = columnOptions.value.find(c => c.id === article.columnId)
        if (existingColumn) {
          selectedColumn.value = existingColumn
        } else {
          // 这里可以调用获取专栏详情的API来获取专栏信息
          selectedColumn.value = {
            id: article.columnId,
            name: article.columnName || '未知专栏'
          }
        }
      }
    } else {
      ElMessage.error('加载文章失败')
      router.push('/article')
    }
  } catch (error) {
    console.error('加载文章失败:', error)
    ElMessage.error('加载文章失败')
    router.push('/article')
  }
}

const saveDraft = async () => {
  if (!validateForm()) return

  saving.value = true
  try {
    const data = {
      ...form.value,
      status: 1
    }

    let response
    if (form.value.id) {
      response = await updateArticle(data)
    } else {
      response = await createArticle(data)
    }

    if (response.code === 200) {
      form.value.id = response.data.id
      ElMessage.success('草稿保存成功')
    } else {
      ElMessage.error(response.message || '保存失败')
    }
  } catch (error) {
    console.error('保存草稿失败:', error)
    ElMessage.error('保存失败')
  } finally {
    saving.value = false
  }
}

const publishArticle = async () => {
  if (!validateForm()) return

  try {
    await ElMessageBox.confirm('确定要发布这篇文章吗？', '确认发布', {
      confirmButtonText: '发布',
      cancelButtonText: '取消',
      type: 'info'
    })

    publishing.value = true
    const data = {
      ...form.value,
      status: 2
    }

    let response
    if (form.value.id) {
      response = await updateArticle(data)
    } else {
      response = await createArticle(data)
    }

    if (response.code === 200) {
      ElMessage.success('文章发布成功')
      router.push(`/article/${response.data.id}`)
    } else {
      ElMessage.error(response.message || '发布失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('发布文章失败:', error)
      ElMessage.error('发布失败')
    }
  } finally {
    publishing.value = false
  }
}

// 话题相关方法
const searchTopicsRemote = async (query) => {
  if (!query) {
    topicOptions.value = []
    return
  }

  topicLoading.value = true
  try {
    const response = await searchTopics({ keyword: query, limit: 20 })
    if (response.code === 200) {
      topicOptions.value = response.data || []
    }
  } catch (error) {
    console.error('搜索话题失败:', error)
  } finally {
    topicLoading.value = false
  }
}

const handleTopicChange = (topicIds) => {
  // 限制最多选择5个话题
  if (topicIds.length > 5) {
    ElMessage.warning('最多只能选择5个话题')
    form.value.topicIds = topicIds.slice(0, 5)
    return
  }

  // 更新已选择的话题信息
  selectedTopics.value = topicOptions.value.filter(topic =>
    form.value.topicIds.includes(topic.id)
  )
}

const removeTopicTag = (topicId) => {
  form.value.topicIds = form.value.topicIds.filter(id => id !== topicId)
  selectedTopics.value = selectedTopics.value.filter(topic => topic.id !== topicId)
}

// 专栏相关方法
const searchColumnsRemote = async (query) => {
  if (!query) {
    columnOptions.value = []
    return
  }

  columnLoading.value = true
  try {
    const response = await getColumnList({
      keyword: query,
      pageNum: 1,
      pageSize: 20,
      userId: userStore.userInfo?.userId // 只搜索当前用户的专栏
    })
    if (response.code === 200) {
      columnOptions.value = response.data.data || []
    }
  } catch (error) {
    console.error('搜索专栏失败:', error)
  } finally {
    columnLoading.value = false
  }
}

// 加载用户的专栏列表
const loadUserColumns = async () => {
  try {
    const response = await getColumnList({
      pageNum: 1,
      pageSize: 50,
      userId: userStore.userInfo?.userId
    })
    if (response.code === 200) {
      columnOptions.value = response.data.data || []
    }
  } catch (error) {
    console.error('加载专栏列表失败:', error)
  }
}

const validateForm = () => {
  if (!form.value.title.trim()) {
    ElMessage.warning('请输入文章标题')
    return false
  }

  if (!form.value.content.trim()) {
    ElMessage.warning('请输入文章内容')
    return false
  }

  return true
}
</script>

<style lang="scss" scoped>
.write-page {
  min-height: 100vh;
  background: #f7f8fa;
}

.editor-container {
  max-width: 900px;
  margin: 0 auto;
  background: white;
  min-height: 100vh;
}

.editor-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;
  background: white;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-left {
  .back-btn {
    color: #8590a6;

    &:hover {
      color: #1890ff;
    }
  }
}

.header-right {
  display: flex;
  gap: 12px;
}

.editor-content {
  padding: 32px 24px;
}

.title-section {
  margin-bottom: 24px;

  .title-input {
    :deep(.el-input__wrapper) {
      border: none;
      box-shadow: none;
      padding: 0;
    }

    :deep(.el-input__inner) {
      font-size: 32px;
      font-weight: 600;
      color: #1a1a1a;

      &::placeholder {
        color: #c4c6cf;
      }
    }
  }
}

.summary-section {
  margin-bottom: 24px;

  .summary-input {
    :deep(.el-textarea__inner) {
      border: none;
      box-shadow: none;
      padding: 0;
      font-size: 16px;
      color: #666;
      resize: none;

      &::placeholder {
        color: #c4c6cf;
      }
    }
  }
}

.topic-section {
  margin-bottom: 24px;

  .section-title {
    font-size: 16px;
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 16px;
  }

  .topic-selector {
    .topic-select {
      width: 100%;
      margin-bottom: 16px;

      :deep(.el-select__wrapper) {
        border: 1px solid #e1e8ed;
        border-radius: 6px;
        padding: 8px 12px;
      }
    }

    .topic-option {
      .topic-name {
        font-size: 14px;
        font-weight: 500;
        color: #1a1a1a;
        margin-bottom: 4px;
      }

      .topic-desc {
        font-size: 12px;
        color: #8590a6;
        line-height: 1.4;
      }
    }

    .selected-topics {
      display: flex;
      flex-wrap: wrap;
      gap: 8px;

      .topic-tag {
        background: #f0f2f5;
        border: 1px solid #e1e8ed;
        color: #1a1a1a;
        font-size: 13px;
        padding: 4px 8px;
        border-radius: 4px;

        &:hover {
          background: #e6f7ff;
          border-color: #91d5ff;
        }
      }
    }
  }
}

.column-section {
  margin-bottom: 24px;

  .section-title {
    font-size: 16px;
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 16px;
  }

  .column-selector {
    .column-select {
      width: 100%;
      margin-bottom: 16px;

      :deep(.el-select__wrapper) {
        border: 1px solid #e1e8ed;
        border-radius: 6px;
        padding: 8px 12px;
      }
    }

    .column-option {
      .column-name {
        font-size: 14px;
        font-weight: 500;
        color: #1a1a1a;
        margin-bottom: 4px;
      }

      .column-desc {
        font-size: 12px;
        color: #8590a6;
        line-height: 1.4;

        @include text-ellipsis;
      }
    }

    .selected-column {
      .column-info {
        display: flex;
        align-items: center;
        gap: 8px;
        padding: 8px 12px;
        background: #f0f9ff;
        border: 1px solid #bae7ff;
        border-radius: 6px;
        font-size: 14px;
        color: #1890ff;

        .remove-btn {
          margin-left: auto;
          color: #8590a6;

          &:hover {
            color: #ff4d4f;
          }
        }
      }
    }
  }
}

.editor-section {
  .section-title {
    font-size: 16px;
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 16px;
  }

  .editor-wrapper {
    border: 1px solid #e1e8ed;
    border-radius: 6px;
    overflow: hidden;

    .content-editor {
      :deep(.el-textarea__inner) {
        border: none;
        box-shadow: none;
        padding: 16px;
        font-size: 16px;
        line-height: 1.8;
        color: #1a1a1a;
        resize: none;

        &::placeholder {
          color: #c4c6cf;
        }
      }
    }
  }
}

.cover-section {
  margin-bottom: 24px;

  .section-title {
    font-size: 16px;
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 12px;
  }

  .cover-uploader {
    :deep(.el-upload) {
      border: 2px dashed #d9d9d9;
      border-radius: 6px;
      cursor: pointer;
      position: relative;
      overflow: hidden;
      transition: all 0.2s;

      &:hover {
        border-color: #1890ff;
      }
    }
  }

  .cover-image {
    width: 200px;
    height: 120px;
    object-fit: cover;
    display: block;
  }

  .cover-placeholder {
    width: 200px;
    height: 120px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #8590a6;

    .upload-icon {
      font-size: 28px;
      margin-bottom: 8px;
    }

    .upload-text {
      font-size: 14px;
    }
  }

  .remove-cover-btn {
    margin-top: 8px;
  }
}

.topics-section {
  margin-bottom: 24px;

  .section-title {
    font-size: 16px;
    font-weight: 500;
    color: #1a1a1a;
    margin-bottom: 12px;
  }

  .topics-select {
    width: 100%;
  }
}
</style>
